package com.shqcjd.devicestatus;

import android.util.Log;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.math.RoundingMode;


public class MQTTTest {

	public void start() {
		System.out.print("hello world");
		
		 String HOST = "tcp://47.100.122.174:1883";
	     String TOPIC = "application/6/device/+/rx";
	     int qos = 1;
	     String clientid = "subClient";
	     String userName = "test";
	     String passWord = "test";
	     try {
	            // host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
	            final MqttClient client = new MqttClient(HOST, clientid, new MemoryPersistence());
	            // MQTT的连接设置
	            MqttConnectOptions options = new MqttConnectOptions();
	            // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
	            options.setCleanSession(true);
	            // 设置连接的用户名
	            options.setUserName(userName);
	            // 设置连接的密码
	            options.setPassword(passWord.toCharArray());
	            // 设置超时时间 单位为秒
	            options.setConnectionTimeout(10);
	            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
	            options.setKeepAliveInterval(20);
	            options.setAutomaticReconnect(true);
	            
	            // 设置回调函数
	            client.setCallback(new MqttCallbackExtended() {

	                public void connectionLost(Throwable cause) {
	                    Log.e("tou","connectionLost");
                        Log.e("tou",cause.toString());
	                    try {
							client.reconnect();
						} catch (Exception e) {
							e.printStackTrace();
						}
	                }

	                public void messageArrived(String topic, MqttMessage message) throws Exception {
                        Log.e("tou","topic:"+topic);
                        Log.e("tou","Qos:"+message.getQos());
	                    String content = new String(message.getPayload());
//                        Log.e("tou","message content:"+new String(message.getPayload()));
//	                    ObjectMapper objectMapper = new ObjectMapper();
//	                    String data = "";
//	            		try {
//	            			JsonNode jsonNode = objectMapper.readTree(content);
//	            			data = jsonNode.get("data").textValue();
//                            Log.e("tou","data:{}", data);
//
//
//	            		} catch (IOException e) {
//	            			// TODO 自动生成的 catch 块
//	            			e.printStackTrace();
//	            		}
                        String data = "";
                        JSONObject jsonObject = new JSONObject(content);
                        data = jsonObject.getString("data");
	                    extractData(data);
	                }

	                public void deliveryComplete(IMqttDeliveryToken token) {
                        Log.e("tou","deliveryComplete---------"+ token.isComplete());
	                }

					@Override
					public void connectComplete(boolean reconnect, String serverURI) {
                        Log.e("tou","重连成功");
					}

	            });
	            
	            client.connect(options);
	            //订阅消息
	            client.subscribe(TOPIC, qos);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }

	}
	
	private static void extractData(String s) {
		byte[] data = hexStringToByteArray(s);
        byte packet_type = data[0];
        int offset = 1;
        int ts = BitConverter.toInt(data, offset);
        Log.e("tou","ts:{}"+ts);

        offset += 4;
        int pk_num = BitConverter.toInt(data, offset);
        Log.e("tou","pk_num:{}"+ pk_num);

        offset += 2;
        short sts = BitConverter.toShort(data, offset);
        Log.e("tou","sts:{}"+ sts);

        offset += 2;
        short bat_voltage = BitConverter.toShort(data, offset);
        Log.e("tou","bat_voltage:{}"+ bat_voltage);

        offset += 2;
        float temp = BitConverter.toFloat(data, offset); // 温度 单位℃
        Log.e("tou","temp:{}"+ temp);

        offset += 4;
        float xrms = BitConverter.toFloat(data, offset);// X轴震动 单位mm/秒
        Log.e("tou","xrms:{}"+ xrms);

        offset += 4;
        float yrms = BitConverter.toFloat(data, offset);// Y轴震动 单位mm/秒
        Log.e("tou","yrms:{}"+ yrms);

        offset += 4;
        float zrms = BitConverter.toFloat(data, offset);// Z轴震动 单位mm/秒
        Log.e("tou","zrms:{}"+ zrms);

        offset += 4;
        float xvrms = BitConverter.toFloat(data, offset);
        Log.e("tou","xvrms:{}"+ xvrms);

        offset += 4;
        float yvrms = BitConverter.toFloat(data, offset);
        Log.e("tou","yvrms:{}"+ yvrms);

        offset += 4;
        float zvrms = BitConverter.toFloat(data, offset);
        Log.e("tou","zvrms:{}"+ zvrms);

        offset += 4;
        float xdrms = BitConverter.toFloat(data, offset);
        Log.e("tou","xdrms:{}"+ xdrms);

        offset += 4;
        float ydrms = BitConverter.toFloat(data, offset);
        Log.e("tou","ydrms:{}"+ ydrms);

        offset += 4;
        float zdrms = BitConverter.toFloat(data, offset);
        Log.e("tou","zdrms:{}"+ zdrms);

        offset += 4;
        float xaver = BitConverter.toFloat(data, offset);
        Log.e("tou","xaver:{}"+ xaver);

        offset += 4;
        float yaver = BitConverter.toFloat(data, offset);
        Log.e("tou","yaver:{}"+ yaver);

        offset += 4;
        float zaver = BitConverter.toFloat(data, offset);
        Log.e("tou","zaver:{}"+ zaver);

        offset += 4;
        short xfreq = BitConverter.toShort(data, offset);
        Log.e("tou","xfreq:{}"+ xfreq);

        offset += 2;
        short yfreq = BitConverter.toShort(data, offset);
        Log.e("tou","yfreq:{}"+ yfreq);

        offset += 2;
        short zfreq = BitConverter.toShort(data, offset);
        Log.e("tou","zfreq:{}"+ zfreq);

        offset += 2;
        int crc = BitConverter.toInt(data, offset);
        Log.e("tou","crc:{}"+ crc);
       
        BigDecimal t = new BigDecimal(String.valueOf(temp));
        String strTemp =  t.setScale(2, RoundingMode.HALF_UP).toString();
        
        BigDecimal x = new BigDecimal(String.valueOf(temp));
        String strX =  x.setScale(2, RoundingMode.HALF_UP).toString();
        
        BigDecimal y = new BigDecimal(String.valueOf(temp));
        String strY =  y.setScale(2, RoundingMode.HALF_UP).toString();
        
        BigDecimal z = new BigDecimal(String.valueOf(temp));
        String strZ =  z.setScale(2, RoundingMode.HALF_UP).toString();
        Log.e("tou", "strTemp: "+strTemp+"---strX: "+strX+"---strY: "+strY+"---strZ: "+strZ);
	}
	
	public static byte[] hexStringToByteArray(String hex) {
        if (hex.length() < 1) {
            return null;
        } else {
            byte[] result = new byte[hex.length() / 2];
            int j = 0;
            for(int i = 0; i < hex.length(); i+=2) {
                result[j++] = (byte) Integer.parseInt(hex.substring(i,i+2), 16);
            }
            return result;
        }
    }

}
